package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import com.example.farmrental.repository.MachineryRepository;
import com.example.farmrental.repository.RentalOrderItemRepository;
import com.example.farmrental.repository.RentalOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@RestController
@RequestMapping("/api/stats")
@CrossOrigin(origins = "*")
public class StatsController {

    @Autowired private MachineryRepository machineryRepository;
    @Autowired private RentalOrderRepository orderRepository;
    @Autowired private RentalOrderItemRepository itemRepository;

    // 概览：在库农机总数、出租中订单、今日新增订单、待接单订单
    @GetMapping("/overview")
    public ResponseEntity<ApiResponse<Map<String, Long>>> overview() {
        Map<String, Long> data = new HashMap<>();
        long totalMachines = machineryRepository.count();
        long rentingOrders = orderRepository.countByStatus("出租中");
        LocalDate today = LocalDate.now();
        LocalDateTime start = today.atStartOfDay();
        LocalDateTime end = today.atTime(LocalTime.MAX);
        long todayOrders = orderRepository.countByOrderTimeBetween(start, end);
        long pendingOrders = orderRepository.countByStatus("待接单");
        data.put("totalMachines", totalMachines);
        data.put("rentingOrders", rentingOrders);
        data.put("todayOrders", todayOrders);
        data.put("pendingOrders", pendingOrders);
        return ResponseEntity.ok(ApiResponse.success("获取统计成功", data));
    }

    // 近七日订单趋势（用于首页演示）
    @GetMapping("/weekly-orders")
    public ResponseEntity<ApiResponse<Map<String, Object>>> weeklyOrders() {
        LocalDate today = LocalDate.now();
        LocalDate startDate = today.minusDays(6);
        LocalDateTime start = startDate.atStartOfDay();
        LocalDateTime end = today.atTime(LocalTime.MAX);

        List<Object[]> rows = orderRepository.countDaily(start, end);
        Map<String, Long> dayCount = new HashMap<>();
        for (Object[] r : rows) {
            String d = String.valueOf(r[0]);
            Long c = ((Number) r[1]).longValue();
            dayCount.put(d, c);
        }
        List<String> dates = new ArrayList<>();
        List<Long> counts = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDate d = today.minusDays(i);
            String key = d.toString();
            dates.add(d.getMonthValue() + "-" + d.getDayOfMonth());
            counts.add(dayCount.getOrDefault(key, 0L));
        }
        Map<String, Object> data = new HashMap<>();
        data.put("dates", dates);
        data.put("orders", counts);
        return ResponseEntity.ok(ApiResponse.success("获取近七日订单成功", data));
    }

    // 热门农机 Top N
    @GetMapping("/popular-machinery")
    public ResponseEntity<ApiResponse<Map<String, Object>>> popularMachinery(@RequestParam(defaultValue = "5") int top) {
        List<Object[]> rows = itemRepository.topPopular(top);
        List<String> names = new ArrayList<>();
        List<Long> counts = new ArrayList<>();
        for (Object[] r : rows) { names.add(String.valueOf(r[0])); counts.add(((Number) r[1]).longValue()); }
        Map<String, Object> data = new HashMap<>();
        data.put("names", names); data.put("counts", counts);
        return ResponseEntity.ok(ApiResponse.success("获取热门农机成功", data));
    }

    // 报表：range=yesterday|week|month
    @GetMapping("/report")
    public ResponseEntity<ApiResponse<Map<String, Object>>> report(@RequestParam String range,
                                                                   @RequestParam(defaultValue = "5") int top) {
        LocalDate today = LocalDate.now();
        LocalDateTime start;
        LocalDateTime end;
        if ("yesterday".equalsIgnoreCase(range)) {
            LocalDate y = today.minusDays(1);
            start = y.atStartOfDay();
            end = y.atTime(LocalTime.MAX);
        } else if ("month".equalsIgnoreCase(range)) {
            LocalDate first = today.withDayOfMonth(1);
            start = first.atStartOfDay();
            end = today.atTime(LocalTime.MAX);
        } else {
            int dow = today.getDayOfWeek().getValue();
            LocalDate monday = today.minusDays(dow - 1);
            start = monday.atStartOfDay();
            end = today.atTime(LocalTime.MAX);
        }

        Map<String, Object> res = new HashMap<>();

        // 营业额趋势
        Map<String, Object> revenue = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<java.math.BigDecimal> series = new ArrayList<>();
        if ("yesterday".equalsIgnoreCase(range)) {
            String ds = start.toLocalDate().toString();
            List<Object[]> rows = orderRepository.sumHourlyByDate(ds);
            Map<Integer, java.math.BigDecimal> map = new HashMap<>();
            for (Object[] r : rows) { map.put(((Number) r[0]).intValue(), toBigDecimal(r[1])); }
            for (int h=0; h<24; h++) { xAxis.add(String.format("%02d:00", h)); series.add(map.getOrDefault(h, java.math.BigDecimal.ZERO)); }
        } else {
            List<Object[]> rows = orderRepository.sumDaily(start, end);
            Map<String, java.math.BigDecimal> map = new HashMap<>();
            for (Object[] r : rows) { map.put(String.valueOf(r[0]), toBigDecimal(r[1])); }
            LocalDate d0 = start.toLocalDate(); LocalDate d1 = end.toLocalDate();
            for (LocalDate d = d0; !d.isAfter(d1); d = d.plusDays(1)) {
                String key = d.toString();
                String label = "week".equalsIgnoreCase(range) ? toWeekLabel(d.getDayOfWeek().getValue()) : String.valueOf(d.getDayOfMonth());
                xAxis.add(label); series.add(map.getOrDefault(key, java.math.BigDecimal.ZERO));
            }
        }
        revenue.put("xAxis", xAxis); revenue.put("data", series); res.put("revenue", revenue);

        // 订单状态统计（直接使用数据库返回的分组，避免字符集不一致导致匹配不到）
        List<Object[]> statusRows = orderRepository.statusGroup(start, end);
        List<String> statusNames = new ArrayList<>();
        List<Long> statusCounts = new ArrayList<>();
        for (Object[] r : statusRows) { statusNames.add(String.valueOf(r[0])); statusCounts.add(((Number) r[1]).longValue()); }
        Map<String, Object> orders = new HashMap<>();
        orders.put("xAxis", statusNames); orders.put("data", statusCounts); res.put("orders", orders);

        // 租赁排名（Top N）
        List<Object[]> topRows = itemRepository.topPopularInRange(start, end, top);
        List<String> names = new ArrayList<>(); List<Long> counts = new ArrayList<>();
        for (Object[] r : topRows) { names.add(String.valueOf(r[0])); counts.add(((Number) r[1]).longValue()); }
        Map<String, Object> ranking = new HashMap<>(); ranking.put("yAxis", names); ranking.put("data", counts); res.put("ranking", ranking);

        return ResponseEntity.ok(ApiResponse.success("报表统计成功", res));
    }

    private String toWeekLabel(int v){
        switch (v){ case 1: return "周一"; case 2: return "周二"; case 3: return "周三"; case 4: return "周四"; case 5: return "周五"; case 6: return "周六"; default: return "周日"; }
    }

    private java.math.BigDecimal toBigDecimal(Object o){
        if (o == null) return java.math.BigDecimal.ZERO;
        if (o instanceof java.math.BigDecimal) return (java.math.BigDecimal)o;
        if (o instanceof Number) return new java.math.BigDecimal(((Number)o).toString());
        return new java.math.BigDecimal(String.valueOf(o));
    }
}

